//
//  JoinProjectSelectViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/2/26.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
class JoinProjectSelectViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var model : LCProjectListModel?
    
    var currentInfo: MWDetailinfoModel? {
        willSet {
            self.currentInfo = newValue
        }
    }
    
    lazy var addDialog:CustomDialog = {
        var dialog = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "确定要加入该项目中吗？", _submitclick: {
            self.addDialog.dismiss()
            self.joinOtherProject()
            
        })
        return dialog
    }()
    
    lazy var dataArray : [LCProjectListModel] = [LCProjectListModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupDemandWorkProjectListSelect()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.navigationItem.title = "加入项目"
        self.tableView.register(UINib.init(nibName: "LCProjectCell", bundle: nil), forCellReuseIdentifier: "ProjectCell")
    }
    
    fileprivate func setupDemandWorkProjectListSelect(){
        QWTextWithStatusHud("正在载入数据...", target: self.view)
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        /*guard let DemandBaseMigrantWorkerID = currentInfo?.DemandBaseMigrantWorkerID else {
            return
        }*/
        
        if self.currentInfo?.DemandBaseMigrantWorkerID == nil{
            
            MWApiMainManager.request(.GetLCProjectNoIdListData(pageIndex: 1, pageSize: 100, IsShowFinish: true, AccountId: accountId)) { (result) in
                if case let .success(response) = result {
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        return
                    }
                    print(jsonString)
                    guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                        return
                    }
                    guard let itemsArray = resultDic["Items"] as? NSArray else{
                        return
                    }
                    self.dataArray = Mapper<LCProjectListModel>().mapArray(JSONObject: itemsArray)!
                    self.tableView.reloadData()
                    QWHudDiss(self.view)
                }
            }
            
        }else{
            
            MWApiMainManager.request(.GetLCProjectListData(pageIndex: 1, pageSize: 100, IsShowFinish: true, DemandBaseMigrantWorkerID: (self.currentInfo?.DemandBaseMigrantWorkerID)!, AccountId: accountId)) { (result) in
                if case let .success(response) = result {
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        return
                    }
                    print(jsonString)
                    guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                        return
                    }
                    guard let itemsArray = resultDic["Items"] as? NSArray else{
                        return
                    }
                    self.dataArray = Mapper<LCProjectListModel>().mapArray(JSONObject: itemsArray)!
                    self.tableView.reloadData()
                    QWHudDiss(self.view)
                }
            }
            
        }
        
        
        
        
    }
}
extension JoinProjectSelectViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.dataArray.count==0{
            self.tableView.isHidden = true
        }else{
            self.tableView.isHidden = false
        }
        return self.dataArray.count
    }
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : LCProjectCell = tableView.dequeueReusableCell(withIdentifier: "ProjectCell") as! LCProjectCell
        cell.setupDataWith(model: self.dataArray[indexPath.row])
        return cell
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 103;
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.model = self.dataArray[indexPath.row]
        
        self.addDialog.show()
    }
    fileprivate func joinOtherProject(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let DemandBaseMigrantWorkerID : String = currentInfo?.MigrantWorkerID else {
            return
        }
        QWTextWithStatusHud("正在处理数据...", target: self.view)
        let workIDListArray = NSMutableArray()
        workIDListArray.add(DemandBaseMigrantWorkerID)
        MWApiMainManager.request(.joinProjectApplication(SupplyBaseId: (self.model?.MarketSupplyBaseID)!, DataItemList: workIDListArray, AccountId: accountId)) { (result) in
            QWHudDiss(self.view)
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    
                    let result = String.init(data: response.data, encoding: String.Encoding.utf8)!
                    print("\(result)")
                    QWTextonlyHud(result, target: self.view)
                    
                    return
                }
                print(jsonString)
                guard let message : String = jsonString["Msg"] as? String else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    QWTextonlyHud(message, target: self.view)
                    return
                }
                QWTextonlyHud("加入成功", target: self.view)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                    self.navigationController?.popViewController(animated: true)
                })
               
            }
        }
    }
}
